import { pinia } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'
import routes from '@/router/config'
import { indexStore } from '@/stores'
import { userStore } from '@/stores/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'


const LoginView = () => import('@/views/LoginView.vue')
const MainContainer = () => import('@/views/MainContainer.vue')
const NotFound = () => import('@/views/NotFound.vue')

const routeStore = indexStore(pinia)
const user = userStore()
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/',
      name: 'main',
      redirect: '/home',
      component: MainContainer,
      children: []
    },
    {
      path: '/:pathMatch(.*)*',
      component: NotFound
    }
  ]
})

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (to.name === 'login') {
    next()
  }
  else if (!localStorage.getItem('token')) {
    next({
      name: 'login'
    })
  }
  else {
    if (routeStore.isGetterRoute) {
      configRoutes()
      next({
        path: to.fullPath
      })
      routeStore.changeGetterRoute(false)
    }
    else {
      next()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

const configRoutes = () => {
  routes.forEach(item => {
    if (!/^user/.test(item.name) || user.userinfo.role === 1)
      router.addRoute('main', item)
  })

}

export default router
